<?php
defined('JOC') or die;
/**
 * Description of mysql
 *
 * @author javier
 */
class mysql
{
  private $link ;
  private $host;
  private $user;
  private $pass;
  private $db;
  private $prefix = '';
  private $result ;
  private $last_id ;
  //put your code here
  function __construct()
  {
    $this->host   = defined('DB_HOST')  ? DB_HOST   : '' ;
    $this->user   = defined('DB_USER')  ? DB_USER   : '' ;
    $this->pass   = defined('DB_PASS')  ? DB_PASS   : '' ;
    $this->db     = defined('DB_DB')    ? DB_DB     : '' ;
    $this->prefix = defined('DB_PREFIX')? DB_PREFIX : '' ;
    $this->connect();
    $this->select_db();
  }
  private function connect()
  {
    $this->link = @mysql_connect($this->host,$this->user,$this->pass);
  }
  private function select_db($db='')
  {
    return @mysql_select_db($db != '' ? $db : $this->db,$this->link);
  }
  function close($link=false)
  {
    return $this->link ? @mysql_close($this->link) : $this->link ;
  }
  function simple_query($sql='')
  {
  	$sql = $this->add_prefix($sql) ;
    return @mysql_query($sql,$this->link);
  }
  function query($sql='',$create_chache=false)
  {
    $this->result = $this->simple_query($sql) ;
    $rows = Array();
    while($row = @mysql_fetch_array($this->result,MYSQL_ASSOC))
    {
      $rows[] = $row ;
    }
    if($create_chache)
    {
      $sql = "INSERT INTO {prefix}cache_query SET cache_id = md5('$sql') ,cache_result ='".serialize($rows)."', cache_last_update = NOW() ,cache_original_query = '$sql' ON DUPLICATE KEY UPDATE cache_last_update = NOW() , cache_result = cache_result ;"  ;
      $this->insert($sql) ;
    }
    return $rows ;
  }
  function insert( $sql = '')
  {
  	$this->simple_query($sql) ;
    $this->last_id = @mysql_insert_id($this->link);
    return $this->last_id ;
  }
  function cache_query($sql = '',$time = 1,$create_chache = true,$free_result = false)
  {
    /*
SELECT cache_result FROM joc_cms_cache_query 
WHERE cache_id = md5('SELECT * FROM test LIMIT 10 ;') 
AND  DATE_SUB( NOW() , INTERVAL 15 MINUTE ) <= cache_last_update  ;
     */
    $sql = "SELECT cache_result FROM {prefix}cache_query WHERE cache_id = md5('$sql') AND cache_last_update > DATE_SUB( NOW() ,INTERVAL $time  MINUTE ) ;" ;
    $result = $this->query($sql,false);
    return !empty($result) && $result[0] && $result[0]['cache_result']? unserialize($result[0]['cache_result']) : false ;
  }
	function add_prefix($sql='')
  {
  	// Here we replace {prefix} with the DB_PREFIX ;
  	return str_replace('{prefix}',$this->prefix,$sql) ;
  }
  function conected()
  {
    return $this->link ? TRUE : FALSE ;
  }
}
